#include <QgsSimulation/DrawPolygonTools.h>

using SimulationCore::QgsSimulation::DrawPolygonTools;

DrawPolygonTools::DrawPolygonTools(QgsMapCanvas *mapcanvas, const QString &action)
	:QgsMapToolEmitPoint(mapcanvas),
	mapcanvas_(mapcanvas), action_(action)

{
	this->crs_ = this->mapcanvas_->mapSettings().destinationCrs();
	this->point_rubber_band_ = new QgsRubberBand(this->mapcanvas_, QgsWkbTypes::PointGeometry);
	this->point_rubber_band_->setColor(Qt::blue);
	this->point_rubber_band_->setWidth(2);
	this->line_rubber_band_ = new QgsRubberBand(this->mapcanvas_, QgsWkbTypes::LineGeometry);
	this->line_rubber_band_->setColor(Qt::blue);
	this->line_rubber_band_->setWidth(2);
}

DrawPolygonTools::~DrawPolygonTools()
{
	this->mapcanvas_->scene()->removeItem(this->point_rubber_band_);
	this->mapcanvas_->scene()->removeItem(this->line_rubber_band_);

	delete this->point_rubber_band_;
	delete this->line_rubber_band_;

	this->point_rubber_band_ = nullptr;
	this->line_rubber_band_ = nullptr;
}

void DrawPolygonTools::canvasPressEvent(QgsMapMouseEvent * e)
{
	if (e->button() == Qt::LeftButton) {
		this->points_ << e->mapPoint();
		this->point_rubber_band_->addPoint(e->mapPoint());
		this->line_rubber_band_->addPoint(e->mapPoint());
	}
	else if (e->button() == Qt::RightButton) {
		if (this->points_.size() > 2) {

			if (this->points_.first() != this->points_.last()) {
				this->points_ << this->points_.first();
			}

			QgsPolygonXY polygon;
			polygon << this->points_;
			auto geometry = QgsGeometry::fromPolygonXY(polygon);
			emit drawGeometry(this->action_, QgsWkbTypes::Polygon, geometry, true);
		}
		ClearGeometry();
	}
}

void DrawPolygonTools::canvasDoubleClickEvent(QgsMapMouseEvent * e)
{
	if (e->button() == Qt::LeftButton && this->points_.size() > 2) {

		if (this->points_.first() != this->points_.last()) {
			this->points_ << this->points_.first();
		}

		QgsPolygonXY polygon;
		polygon << this->points_;
		auto geometry = QgsGeometry::fromPolygonXY(polygon);
		emit drawGeometry(this->action_, QgsWkbTypes::Polygon, geometry, true);
		ClearGeometry();
	}
}

void DrawPolygonTools::deactivate()
{
	ClearGeometry();
	QgsMapToolEmitPoint::deactivate();
}

void SimulationCore::QgsSimulation::DrawPolygonTools::ClearGeometry()
{
	/*Çå³ý»º´æÊý¾Ý*/
	this->points_.clear();
	this->point_rubber_band_->reset(QgsWkbTypes::PointGeometry);
	this->line_rubber_band_->reset(QgsWkbTypes::LineGeometry);
}
